package com.nacos.temp3.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Feign请求拦截器
 */
@Slf4j
//TODO - 注意，已经在配置文件中配置了FeignInterceptor，若此处再加上注解@Component将使拦截器重复执行，两种配置方式选择一种即可
//@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            log.info("Feign请求拦截器 ===>> " + requestTemplate.url());

            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();

            Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    requestTemplate.header(name, httpServletRequest.getHeader(name));
                }
            }
            log.info("接口路径：" + httpServletRequest.getRequestURL().toString());

            Enumeration<String> bodyNames = httpServletRequest.getParameterNames();
            if (bodyNames != null) {
                Map<String, String> map = new HashMap<>();
                while (bodyNames.hasMoreElements()) {
                    String name = bodyNames.nextElement();
                    String values = httpServletRequest.getParameter(name);
                    // 参数转发
                    requestTemplate.query(name, values);
                    map.put(name, values);
                }
                log.info("传入参数：" + map);
            }
        } catch (Exception e) {
            log.error("服务之间的调用,处理请求头发生异常:{}", e.getMessage(), e);
        }
    }

}
